package cn.wx.scholar.core.service;

//import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
//import org.redisson.api.RMapCache;
//import org.redisson.api.RedissonClient;
//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.wx.scholar.core.entity.User;
import cn.wx.scholar.core.entity.dto.LoginDto;
import cn.wx.scholar.core.entity.qo.UserQ;
import cn.wx.common.persistence.base.BaseService;
import cn.wx.common.persistence.exception.MyException;
//import cn.wx.common.persistence.redisson.RS;
import cn.wx.common.persistence.web.ResponseCode;
import cn.wx.scholar.core.mapper.UserMapper;
import cn.wx.scholar.tool.jwt.JwtUtil;

/**
 * <p>
 * 服务类
 * </p>
 *
 * @author
 * @since 2018-09-11
 */
@Service
@Transactional
public class UserService extends BaseService<User, UserMapper> {
	
	/*@Autowired
	private RedissonClient redissonClient;*/
	
	/**
	 * 登录处理
	 * @param userQ
	 * @return
	 */
	public LoginDto login(UserQ userQ) {
		
		if(userQ == null 
				|| StringUtils.isBlank(userQ.getUserName()) 
				|| StringUtils.isBlank(userQ.getPassword())) {
			throw new MyException(ResponseCode.PARAMETER_REQUIRED);
		}
		

		User user = simpleMapper.queryUnique(userQ.getUserName());
		
		/**
		 * 用户不存在 或者 密码错误
		 * 用户匹配失败
		 */
		if (user == null || 
				!userQ.getPassword().equalsIgnoreCase(user.getPassword())) {
			throw new MyException(ResponseCode.NO_USER);
		}

		String jwt = JwtUtil.generateToken(user.getpId());
		
		LoginDto dto = new LoginDto();
		dto.setToken(jwt);
		
		//RMapCache<Long,String> tokens = redissonClient.getMapCache(RS.REDIS_GENETOKEN);
		//tokens.put(user.getpId(), "1", 1, TimeUnit.HOURS , 0, TimeUnit.HOURS);
		
		return dto;
	}
}














